<template>
  <div>
    <cus-modal ref="modal" :title="!form.id ? '添加菜肴' : '修改菜肴'" @on-visible-change="onVisibleChange" width="1100"
      :showOkBtn="form.isPersonalized" :cancelBtnName="cancelBtnName" @onOk="onOk">
      <Form ref="formValidate" :model="form" :rules="ruleValidate" :label-width="100">
        <div style="width:100%;display:flex;flex-wrap:wrap;justify-content: space-between;padding:0 10px">
          <FormItem label="菜肴编码:" prop="dishCode" :rules="{
            required: true,
            message: '菜肴编码不能为空',
            trigger: 'change'
          }">
            <Input v-model="form.dishCode" readonly style="width: 200px" placeholder="菜肴编码自动生成"></Input>
          </FormItem>
          <FormItem label="菜肴名称:" prop="dishName" :rules="{
            required: true,
            message: '菜肴名称不能为空',
            trigger: 'blur'
          }">
            <Input v-model="form.dishName" clearable style="width: 200px" placeholder="请输入菜肴名称"></Input>
          </FormItem>
          <FormItem label="菜肴类别:" prop="dishType" :rules="{
            required: true,
            message: '菜肴类别不能为空',
            trigger: 'change'
          }">
            <Select v-model="form.dishType" style="width:200px" placeholder="请选择菜肴类别" clearable
              @on-change="creatDishcode">
              <Option :value="item.dishCategory" v-for="(item, index) in materialTypeList" :key="index">{{
                item.dishCategory }}</Option>
            </Select>
          </FormItem>
        </div>
        <div style="width:100%;margin-top:15px">
          <Tabs type="card" v-model="tabs1">
            <TabPane label="菜肴属性" name="name1">
              <div style="display:flex;flex-wrap:wrap;justify-content: space-between;padding:0 10px" class="tabsBox">
                <FormItem label="烹饪技法:" prop="skills">
                  <Select v-model="form.skills" style="width:200px" placeholder="请选择烹饪技法" clearable transfer>
                    <template v-for="(item, index) in dishAttributeList">
                      <Option :value="item.value" :key="index" v-if="item.ruleType == 1">{{ item.value }}</Option>
                    </template>
                  </Select>
                </FormItem>
                <FormItem label="汤汁:" prop="soup">
                  <Select v-model="form.soup" style="width:200px" placeholder="请选择汤汁" clearable transfer>
                    <template v-for="(item, index) in dishAttributeList">
                      <Option :value="item.value" :key="index" v-if="item.ruleType == 4">{{ item.value }}</Option>
                    </template>
                  </Select>
                </FormItem>
                <FormItem label="菜肴口味:" prop="taste">
                  <Select v-model="form.taste" style="width:200px" placeholder="请选择菜肴口味" clearable transfer>
                    <template v-for="(item, index) in dishAttributeList">
                      <Option :value="item.value" :key="index" v-if="item.ruleType == 3">{{ item.value }}</Option>
                    </template>
                  </Select>
                </FormItem>
                <FormItem label="菜肴颜色:" prop="colour">
                  <Select v-model="form.colour" style="width:200px" placeholder="请选择菜肴颜色" clearable transfer>
                    <template v-for="(item, index) in dishAttributeList">
                      <Option :value="item.value" :key="index" v-if="item.ruleType == 2">{{ item.value }}</Option>
                    </template>
                  </Select>
                </FormItem>
                <FormItem label="烹饪时间(分):" prop="time">
                  <InputNumber :min="0" :step="5" v-model="form.time" style="width:200px"></InputNumber>
                </FormItem>
                <FormItem label="刀工(素菜):" prop="skill1">
                  <Select v-model="form.skill1" style="width:200px" placeholder="请选择刀工(素菜)" clearable transfer>
                    <template v-for="(item, index) in dishAttributeList">
                      <Option :value="item.value" :key="index" v-if="item.ruleType == 7">{{ item.value }}</Option>
                    </template>
                  </Select>
                </FormItem>
                <FormItem label="刀工(荤菜):" prop="skill2">
                  <Select v-model="form.skill2" style="width:200px" placeholder="请选择菜肴刀工(荤菜)" clearable transfer>
                    <template v-for="(item, index) in dishAttributeList">
                      <Option :value="item.value" :key="index" v-if="item.ruleType == 6">{{ item.value }}</Option>
                    </template>
                  </Select>
                </FormItem>
                <FormItem label="生熟比(%):" prop="curingRate">
                  <InputNumber :max="10000" :min="0" v-model="form.curingRate" style="width:200px"></InputNumber>
                </FormItem>
                <FormItem label="">
                  <div style="width:200px"></div>
                </FormItem>
              </div>
            </TabPane>
            <TabPane label="菜肴图片" name="name2">
              <div class="tabsBox dishurlBox">
                <Upload action="" :before-upload="file => {
                  onBeforeUpload(file, 1);
                }
                  " :show-upload-list="false" accept="image/jpg,image/png,image/jpeg">
                  <div class="uploadDishurlBox" v-if="!form.dishUrl">
                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                    <p>
                      点击上传菜肴图片，只能上传 JPG/PNG 格式文件，大小不超过
                      10M.
                    </p>
                  </div>
                  <div class="demo-upload-list" v-else>
                    <img :src="form.dishUrl" class="dishUrlImg" />
                    <div class="demo-upload-list-cover">替换</div>
                  </div>
                  <div v-if="form.dishUrl" style="tex-align:center;margin-top:2px;width:100%">
                    <Button style="width:140px" @click.native.stop="$cu.previewImage(form.dishUrl)">查看大图</Button>
                  </div>
                </Upload>
              </div>
            </TabPane>
          </Tabs>
          <Tabs type="card" style="margin-top:15px" v-model="tabs2">
            <TabPane label="BOM食材" name="type1">
              <div class="bomBox tabsBox">
                <div style="text-align:right;margin-bottom:10px">
                  <Button type="primary" @click="addBomItem" v-if="form.isPersonalized">添加</Button>
                </div>
                <Table border :columns="columns" :data="data">
                  <template slot-scope="{ row, index }" slot="operation" v-if="form.isPersonalized">
                    <div class="flex">
                      <cus-button type="text" size="small" :style="{ color: '#FF4746', padding: '0 8px' }"
                        @onClick="data.splice(index, 1)">
                        删除
                      </cus-button>
                    </div>
                  </template>
                </Table>
              </div>
            </TabPane>
            <TabPane label="工艺图片/视频" name="type2">
              <div class="tabsBox gongBox">
                <div>
                  <Upload action="" :before-upload="file => {
                    onBeforeUpload(file, 2);
                  }
                    " :show-upload-list="false" accept="image/jpg,image/png,image/jpeg">
                    <div class="uploadDishurlBox" v-if="!form.cookPicture" style="padding:20px">
                      <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                      <p>
                        点击上<span style="color:green;font-weight:bold">
                          工艺图片
                        </span>
                      </p>
                      <p>只能上传 JPG/PNG 格式文件，大小不超过 10M.</p>
                    </div>
                    <div class="demo-upload-list" v-else>
                      <img :src="form.cookPicture" class="dishUrlImg" />
                      <div class="demo-upload-list-cover">替换工艺图片</div>
                    </div>
                    <div v-if="form.cookPicture" style="tex-align:center;margin-top:2px;width:100%">
                      <Button style="width:140px" @click.native.stop="$cu.previewImage(form.cookPicture)">查看大图</Button>
                    </div>
                  </Upload>
                </div>
                <div>
                  <Upload action="" :before-upload="file => {
                    onBeforeUpload(file, 3);
                  }
                    " :show-upload-list="false" accept=".mp4">
                    <div class="uploadDishurlBox" v-if="!form.cookVideo" style="padding:20px">
                      <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                      <p>
                        点击上<span style="color:green;font-weight:bold">
                          工艺视频
                        </span>
                      </p>
                      <p>只能上传 MP4 格式文件，大小不超过 500M.</p>
                    </div>
                    <video controls autoplay name="media" v-else style="width:342px!important;height:140px!important">
                      <source :src="form.cookVideo" type="video/mp4" />
                    </video>
                    <div v-if="form.cookVideo" style="margin-top:2px;width:100%;text-align:center;">
                      <Button style="width:140px;">替换视频</Button>
                    </div>
                  </Upload>
                </div>
              </div>
            </TabPane>
            <TabPane label="烹饪方法" name="type3">
              <div class="tabsBox gongBox">
                <div>
                  <div style="margin-bottom:10px">制作工艺</div>
                  <Input v-model="form.craft" type="textarea" :autosize="{ minRows: 5, maxRows: 10 }"
                    placeholder="请输入制作工艺" style="width:300px;" />
                </div>
                <div>
                  <div style="margin-bottom:10px">烹饪工艺</div>
                  <Input v-model="form.cookCraft" type="textarea" :autosize="{ minRows: 5, maxRows: 10 }"
                    placeholder="请输入烹饪工艺" style="width:300px;" />
                </div>
              </div>
            </TabPane>
          </Tabs>
        </div>
      </Form>

    </cus-modal>
    <!-- 添加子BOM -->
    <addTableitemModal ref="addTableitemModal" @addItem="addItem"></addTableitemModal>
  </div>
</template>

<script>
import {
  getDishListType,
  getDishAttributeValue,
  basicUploadFill,
  localDishAdd,
  getDishCode,
  getDishAllInfo
} from "@/api/business/dishesModule";
import addTableitemModal from "./addTableitemModal";

const form = {
  id: "",
  dishCode: "", // 菜肴编码
  dishName: "", // 菜肴名称，字符限制20
  dishType: "", // 菜肴分类
  // dishUrl: "https://img1.baidu.com/it/u=1334904732,3210582282&fm=253&fmt=auto&app=120&f=JPEG?w=605&h=500", // 菜肴图片
  dishUrl: "",
  colour: "", // 菜肴颜色
  skill1: "", // 植物刀工形状
  skill2: "", // 动物刀工形状
  skills: "", // 烹饪技法
  soup: "", // 汤汁
  taste: "", // 菜肴口味
  time: 0, // 烹饪时间
  curingRate: 100, // 生熟比
  cookPicture: "", // 工艺图片
  // cookVideo: "http://172.16.1.75:11570/statics/video/AAAAA.mp4", // 工艺视频
  cookVideo: "", // 工艺视频
  cookCraft: "", // 烹饪工艺
  craft: "", // 制作工艺
  isPersonalized: 1 //是否为个性化菜肴
};

export default {
  name: "addDishesModal",
  components: { addTableitemModal },
  data() {
    return {
      form: form,
      ruleValidate: {},
      materialTypeList: [], // 菜肴分类列表
      dishAttributeList: [], // 刀工、味型等列表
      basicUploadFill: basicUploadFill,
      data: [], // BOM食材列表
      columns: [
        {
          title: "序号",
          width: 70,
          type: "index",
          align: "center"
        },
        {
          title: "食材分类",
          key: "materialClass",
          align: "center"
        },
        {
          title: "食材名称",
          key: "materialName",
          align: "center"
        },
        {
          title: "下料量/人份",
          key: "weight",
          align: "center"
        },
        {
          title: "计量单位",
          key: "specification",
          align: "center"
        }
      ],
      tabs1: "name1",
      tabs2: "type1",
      cancelBtnName: "关闭"
    };
  },
  mounted() {
    this.form = this.$cu.deepClone(form);
  },
  methods: {
    onVisibleChange(v) {
      if (!v) {
        this.$refs["formValidate"].resetFields();
        this.form = this.$cu.deepClone(form);
        this.data = [];
        this.tabs1 = "name1";
        this.tabs2 = "type1";
      }
    },
    show() {
      this.$refs["modal"].show = true;
      if (this.form.dishCode) {
        this.getDishAllInfoApi();
      }
      this.getDishListTypeApi();
      this.getDishAttributeValueApi();
    },
    onOk() {
      // if (!this.data.length) {
      //   this.$Message.warning("请至少添加一条BOM食材信息后再提交.");
      //   return;
      // }
      this.$refs["formValidate"].validate(valid => {
        if (valid) {
          this.localDishAddApi();
        }
      });
    },
    // 保存
    localDishAddApi() {
      this.loading = true;
      return new Promise(resolve => {
        let obj = {
          // 菜肴信息
          dish: {
            curingRate: this.form.curingRate,
            dishCode: this.form.dishCode,
            dishName: this.form.dishName,
            dishType: this.form.dishType,
            dishUrl: this.form.dishUrl,
            id: this.form.id
          },
          // 菜肴属性
          dishAttribute: {
            colour: this.form.colour,
            skill1: this.form.skill1,
            skill2: this.form.skill2,
            skills: this.form.skills,
            soup: this.form.soup,
            taste: this.form.taste,
            time: this.form.time
          },
          // 菜肴配料
          dishChineseBom: {
            chineseBomFoods: this.data,
            dishPerson: ""
          },
          // 菜肴工艺
          dishMake: {
            cookCraft: this.form.cookCraft,
            craft: this.form.craft,
            cookPicture: this.form.cookPicture,
            cookVideo: this.form.cookVideo
          }
        };
        localDishAdd(obj).then(res => {
          this.loading = false;
          if (res.retCode === 2000) {
            this.$Message.success(
              !this.form.id ? "添加菜肴成功." : "编辑菜肴成功."
            );
            this.$refs["modal"].show = false;
            this.$parent.onInit();
            resolve();
          }
        });
      });
    },
    // 获取菜肴分类
    getDishListTypeApi() {
      return new Promise(resolve => {
        getDishListType({}).then(res => {
          if (res.retCode === 2000) {
            this.materialTypeList = res.data;
            resolve();
          }
        });
      });
    },
    // 获取菜肴属性值列表
    getDishAttributeValueApi() {
      return new Promise(resolve => {
        getDishAttributeValue({
          ruleType: 0
        }).then(res => {
          if (res.retCode === 2000) {
            this.dishAttributeList = res.data;
            resolve();
          }
        });
      });
    },
    // 上传菜肴图片
    onBeforeUpload(file, type) {
      if (!this.form.dishName) {
        this.$Message.warning("请先填写菜肴名称再上传菜肴图片.");
        return false;
      }
      // 控制文件上传大小
      var Maxsize = 1024 * 10 * 1024;
      console.log("file.size--" + file.size);
      if (type == 1) {
        if (file.size > Maxsize) {
          this.$Message.warning("菜肴图片大小不能超过 10M.");
          return false;
        }
      }
      if (type == 2) {
        if (file.size > Maxsize) {
          this.$Message.warning("工艺图片大小不能超过 10M.");
          return false;
        }
      }
      if (type == 3) {
        Maxsize = 500 * 1024 * 1024;
        if (file.size > Maxsize) {
          this.$Message.warning("工艺视频大小不能超过 500M.");
          return false;
        }
      }
      if (file) {
        this.$cu.showLoading();
        let params = new FormData();
        params.append("file", file);
        params.append("fileName", this.form.dishName);
        params.append("type", type); // type 1 菜肴图片， 2 工艺图片 ， 3 菜肴视频

        this.basicUploadFill(params)
          .then(res => {
            if (res.code === 1 || res.retCode === 2000) {
              this.$cu.hideLoading();
              this.$Message.success("上传成功");
              if (type == 1) {
                this.form.dishUrl = res.data + "?time=" + new Date().getTime();
              }
              if (type == 2) {
                this.form.cookPicture =
                  res.data + "?time=" + new Date().getTime();
              }
              if (type == 3) {
                this.form.cookVideo =
                  res.data + "?time=" + new Date().getTime();
              }
            } else {
              this.$cu.hideLoading(1.5);
            }
          })
          .catch(() => this.$cu.hideLoading(1.5));
      }
      return false;
    },
    // 添加子BOM
    addBomItem() {
      this.$refs["addTableitemModal"].show();
    },
    addItem(option) {
      let canPush = false;
      if (this.data.length > 0) {
        canPush = this.data.some(item => {
          return item.materialId == option.materialId;
        });
        if (canPush) {
          this.$Message.error(`已经添加过${option.materialName}`);
        } else {
          this.data.push(option);
          this.$refs["addTableitemModal"].onCancel();
        }
      } else {
        this.data.push(option);
        this.$refs["addTableitemModal"].onCancel();
      }
    },
    creatDishcode() {
      if (!this.form.dishCode && this.form.dishType) {
        getDishCode({
          dishCategory: this.form.dishType
        }).then(res => {
          if (res.retCode === 2000) {
            this.form.dishCode = res.data;
            resolve();
          }
        });
      }
    },
    // 获取菜肴信息
    getDishAllInfoApi() {
      return new Promise(resolve => {
        getDishAllInfo({
          dishCode: this.form.dishCode
        }).then(res => {
          if (res.retCode === 2000) {
            // this.form = Object.assign({}, res.data.localDish, res.data.attributeVo, res.data.localDishMake)
            this.form = {
              id: res.data.localDish.id,
              dishCode: res.data.localDish.dishCode, // 菜肴编码
              dishName: res.data.localDish.dishName, // 菜肴名称，字符限制20
              dishType: res.data.localDish.dishType, // 菜肴分类
              dishUrl: res.data.localDish.dishUrl
                ? res.data.localDish.dishUrl + "?time=" + new Date().getTime()
                : "",
              isPersonalized: res.data.localDish.isPersonalized, //是否为个性化菜肴
              colour: res.data.attributeVo.colour, // 菜肴颜色
              skill1: res.data.attributeVo.skill1, // 植物刀工形状
              skill2: res.data.attributeVo.skill2, // 动物刀工形状
              skills: res.data.attributeVo.skills, // 烹饪技法
              soup: res.data.attributeVo.soup, // 汤汁
              taste: res.data.attributeVo.taste, // 菜肴口味
              time: res.data.attributeVo.time
                ? parseFloat(res.data.attributeVo.time)
                : 0, // 烹饪时间
              curingRate: res.data.localDish.curingRate || 0, // 生熟比
              cookPicture: res.data.localDishMake.cookPicture
                ? res.data.localDishMake.cookPicture +
                "?time=" +
                new Date().getTime()
                : "", // 工艺图片
              cookVideo: res.data.localDishMake.cookVideo
                ? res.data.localDishMake.cookVideo +
                "?time=" +
                new Date().getTime()
                : "", // 工艺视频
              cookCraft: res.data.localDishMake.cookCraft, // 烹饪工艺
              craft: res.data.localDishMake.craft // 制作工艺
            };
            this.data = res.data.localChineseBom.chineseBomFoods;
            resolve();
          }
        });
      });
    }
  }
};
</script>
<style scoped lang="scss">
::v-deep .ivu-tabs-bar {
  margin-bottom: 0 !important;
}
</style>
<style scoped lang="less">
.permission {
  height: 300px;
  width: 500px;
  border: 1px solid #dcdee2;
  overflow-y: auto;
  border-radius: 2px;
  padding: 0 0 0 10px;
}

.tabsBox {
  padding-top: 25px !important;
  border: 1px solid #d7dde4 !important;
  border-top: none !important;
  border-radius: 0 0 4px 4px;
}

.uploadDishurlBox {
  background: #fff;
  padding: 30px;
  border: 1px dashed #dcdee2;
  border-radius: 4px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.2s ease;
}

.uploadDishurlBox:hover {
  border: 1px dashed #2d8cf0;
}

.dishurlBox {
  padding: 0 10px;
  height: 218px !important;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

.demo-upload-list {
  display: inline-block;
  width: 140px;
  height: 140px;
  text-align: center;
  line-height: 140px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  border: 1px dashed #dcdee2;
}

.dishUrlImg {
  width: 140px !important;
  height: 140px !important;
  border-radius: 4px;
}

.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}

.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  cursor: pointer;
  color: #fff;
}

.bomBox {
  padding: 10px;
}

.gongBox {
  display: flex !important;
  padding: 0 30px 16px;
  align-items: center;
  justify-content: space-around;
}
</style>
